package com.otoe.dilidilivid.view.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.otoe.dilidilivid.R;
import com.otoe.dilidilivid.data.dao.UserDao;
import com.otoe.dilidilivid.data.entity.User;

/**
 * function：连接注册页面
 */
public class RegisterActivity extends AppCompatActivity {
    private static final String TAG = "mysql-SSSS-register";
    EditText usernameEditText = null;
    EditText passwordEditText = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 待指定输入框与变量关系
        usernameEditText=findViewById(R.id.EtUname);
        passwordEditText=findViewById(R.id.EtPassword);
    }


    public void register(View view){
        String uname=usernameEditText.getText().toString();
        String password=passwordEditText.getText().toString();

        User user = new User();
        user.setU_name(uname);
        user.setPassword(password);

        new Thread(() -> {

            int msg = 0;

            UserDao userDao = new UserDao();

            User uu = null;
            try {
                uu = userDao.findUser(user.getU_name());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(uu != null){
                msg = 1;
            }
            else{
                boolean flag = false;
                try {
                    flag = userDao.register(user);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(flag){
                    msg = 2;
                }
            }
            hand.sendEmptyMessage(msg);
        }).start();
    }
    @SuppressLint("HandlerLeak")
    final Handler hand = new Handler()
    {
        public void handleMessage(Message msg) {
            if(msg.what == 0) {
                Toast.makeText(getApplicationContext(),"注册失败",Toast.LENGTH_LONG).show();
            } else if(msg.what == 1) {
                Toast.makeText(getApplicationContext(),"该账号已经存在，请换一个账号",Toast.LENGTH_LONG).show();
            } else if(msg.what == 2) {
                Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    };
}
